package com.wwwarehouse.common.custom_widget.textinput;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;

import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.R;

/**
 * @author : mundane
 * @time : 2017/6/21 9:49
 * @description :
 * @file : KirakiraTextInputLayout.java
 */

public class KirakiraEditText extends ClearEditText {

	private Handler mHandler = new Handler();
	private int mCurrentColor = getResources().getColor(R.color.common_color_c1_337cff);
	private int BLUE_COLOR = getResources().getColor(R.color.common_color_c1_337cff);
	private int TRANSPARENT_COLOR = getResources().getColor(android.R.color.transparent);
	private Runnable mRunnable = new Runnable() {
		@Override
		public void run() {

			if (mCurrentColor == BLUE_COLOR) {
				mCurrentColor = TRANSPARENT_COLOR;
			} else {
				mCurrentColor = BLUE_COLOR;
			}
			mPaint.setColor(mCurrentColor);
			invalidate();
			mHandler.postDelayed(mRunnable, 600);
		}
	};
	private Paint mPaint;
	private final int DEF_BOTTOM_LINE_HEIGHT = 1;

	public KirakiraEditText(Context context) {
		super(context);
		init(context);
	}



	public KirakiraEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public KirakiraEditText(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// 画底线
		canvas.drawLine(0, this.getHeight() - dp2px(DEF_BOTTOM_LINE_HEIGHT)/2, this.getWidth(), this.getHeight() - dp2px(DEF_BOTTOM_LINE_HEIGHT)/2, mPaint);
	}

	private void init(Context context) {
//		setPadding(0, 0, 0, 0);
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG|Paint.DITHER_FLAG);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setColor(mCurrentColor);
		mPaint.setStrokeWidth(dp2px(DEF_BOTTOM_LINE_HEIGHT));
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		mHandler.post(mRunnable);
	}

	@Override
	protected void onDetachedFromWindow() {
		mHandler.removeCallbacksAndMessages(null);
		super.onDetachedFromWindow();
	}

	public int px2dp(float paValue) {
		final float scale = getContext().getResources().getDisplayMetrics().density;
		return (int) (paValue / scale + 0.5f);
	}

	public int dp2px(float dpValue) {
		final float scale = getContext().getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public int px2sp(float pxValue) {
		final float frontScale = getContext().getResources().getDisplayMetrics().scaledDensity;
		return (int) (pxValue / frontScale + 0.5f);
	}

	public int sp2px(float spValue) {
		final float frontScale = getContext().getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * frontScale + 0.5f);
	}
}
